<?php

/* he 教师成绩导入操作 */

class TeacherController extends FController {

    public $user_school_list;
    public $user_subject_list;
    public $user_role_list;
    public $exam_id;
	public function init() {
		parent::init();
		if (empty($this->cLoginUser)) {
			$this->redirect($this->createUrl('/site/login'));
        } else {
            $userLoginUser = $this->cLoginUser;
            $this->user_role_list = isset($userLoginUser['cuser']['role_id']) ? $userLoginUser['cuser']['role_id'] : '';
            $this->user_school_list = isset($userLoginUser['cuser']['school']['school_id']) ? $userLoginUser['cuser']['school']['school_id'] : '';
            $this->user_subject_list = isset($userLoginUser['cuser']['school']['subject_id']) ? $userLoginUser['cuser']['school']['subject_id'] : '';
            $zRow = new ZRole();
            //得到学校对应的考试
            $exam_list = $zRow->_getSchoolExam($this->user_school_list);
            if (!empty($exam_list)) {
                $this->exam_id = implode(',', $exam_list);
            }
		}
		$this->commonScript();
		Yii::app()->clientScript->registerCssFile(THEME_CSS_URL . '/base.css');
		Yii::app()->clientScript->registerCssFile(THEME_CSS_URL . '/master.css');
		Yii::app()->clientScript->registerCssFile(THEME_CSS_URL . '/module_Sip.css');
	}

	//导入
	public function actionIndex() {
		$this->title = '阅卷教师信息导入';

		$conn = Yii::app()->db;
		$limit = 8;

                $where = '';
                if (empty($date['exam_id'])){
                    //权限判断
                    if ($this->user_role_list != 1 && !empty($this->exam_id)) {
                        $where .= ' AND "exam_id" IN (' . $this->exam_id . ')';
                    }
                }
                
		$date['ztask'] = ZTask::_getExamAll($where);
		$schoolwhere = ' WHERE "is_del" =0 ';
        // $schoolwhere = ' WHERE "is_del"=0 ';
        // $date['school'] = Nojoin::_getschoolAll($schoolwhere);
        $zEdu = new ZEdu();
        if ($this->user_role_list != 1 && !empty($this->user_school_list)) {
            $date['school'] = $zEdu->_getSchoolInfo($this->user_school_list);
            $where .= " AND \"school_id\" IN (".$this->user_school_list.") ";
		}else{
            $date['school'] = $zEdu->_getSchoolInfo();
		}
		$date['exam_id'] = $this->request->getParam('exam_id', 0);

		$data_search = $data = $pages = array();
		if ($date['exam_id'] > 0) {

			$sql = ' SELECT *  FROM "{{import_error}}" WHERE "type"=2 AND "exam_id"= ' . $date['exam_id'];
			$count = ' SELECT count("id") FROM "{{import_error}}" WHERE "exam_id" =' . $date['exam_id'];
			$data = ZCommon::getDaoPageList($sql, $count, $limit);
			if (!empty($data)) {
				$pages = isset($data['pages']) ? $data['pages'] : '';
			} else {
                if(!empty($this->user_subject_list) && $this->user_role_list != 1){
                    $where .= " AND \"subject_id\" IN (".$this->user_subject_list.") ";
                }
                $data_teacher = self::_GetTeacherList($where);
				$pages = isset($data_teacher['pages']) ? $data_teacher['pages'] : '';
			}
		} else {
            $data_teacher = self::_GetTeacherList($where);
			$pages = isset($data_teacher['pages']) ? $data_teacher['pages'] : '';
		}

		$pageUrl = $this->createUrl('/info/teacher/index', array('exam_id' => $date['exam_id']));
		$this->render('import', array(
		'data' => isset($data['listDatas'])?$data['listDatas']:'',
		'pages' => $pages,
		'data_teacher' => isset($data_teacher['listDatas']) ? $data_teacher['listDatas'] : '',
		'pageUrl' => $pageUrl,
		'date' => $date
		));
	}

	/**
     * 得到教师列表
     * 
     * @version 1.0
     * @date 2014-01-12
     */
    protected function _GetTeacherList($where='', $pageSize = 8) {

		$conn = Yii::app()->db;

        if(!empty($where)){
            $sql = 'SELECT "teacher_id","teacher_name","subject_name","school_name","exam_id" FROM "{{teacher}}" WHERE 1=1 ' . $where;
            $sqlCount = 'SELECT count(*) FROM "{{teacher}}" WHERE 1=1 ' . $where;
        }else{
            $sql = 'SELECT "teacher_id","teacher_name","subject_name","school_name","exam_id" FROM "{{teacher}}" ';
            $sqlCount = 'SELECT count(*) FROM "{{teacher}}" ';
		}

		$data = ZCommon::getDaoPageList($sql, $sqlCount, $pageSize);

		return $data;
	}

	/**
     * 上传文件
     * 
     * @version 1.0
     * @update 2014-01-21
     */
	public function actionImport() {

		if (!empty($_POST['submit'])) {

			$data = $this->request->getParam('info');

			if (empty($data['exam_id']) || empty($_FILES['file']['name']) || empty($data['school_id'])) {
				$this->redirect('/info/teacher/index/error/1'); exit;
			} else {
				$conn = Yii::app()->db;

				//得到学生信息
				$userinfo = $this->cLoginUser;
				if (!empty($userinfo)) {
					if ($userinfo['cuser']['role_id'] != 1) {   //超级管理员可以导入任何学校
						$userid = $userinfo['cuser']['id'];
						$studentinfo = Import::_getstudentinfo($userid);
						if (empty($studentinfo)){
							$this->redirect('/info/teacher/index/error/9');  exit;
						}
						//判断当前用户是否有导入所选学校的权限
						$school_ids = $studentinfo['school_id'];
						$school_id = $data['school_id'];
						if (!strpos($school_ids, $school_id)) {
							$this->redirect('/info/teacher/index/error/2');  exit;
						}
					}
				}

				//得到项目信息
				$examwhere = ' AND "exam_id" =' . $data['exam_id'];
				$exam = ZTask::_getExamAll($examwhere);

				$exam_where = ' WHERE "exam_id" = ' . $data['exam_id'];
				$exam_school = Nojoin::_getexam_schoolALL($exam_where);

				$exam_school_id = array();
				foreach ($exam_school as $k => $v) {
					$exam_school_id[] = $v['school_id'];
				}

				if (!in_array($data['school_id'], $exam_school_id)) {
					$this->redirect('/info/teacher/index/error/3');  exit;
				}

				//得到科目信息
				$subjectnamestr = '';
				if (isset($exam[0]['exam_subject_ids']) && !empty($exam[0]['exam_subject_ids'])) {
					$subjectcode = "'" . str_replace("-", "','", $exam[0]['exam_subject_ids']) . "'";
					$subjectwhere = ' WHERE "is_del" = 0 AND "subject_code" IN(' . $subjectcode . ')';
					$subjectnames = Nojoin::_getsubjectAll($subjectwhere);

					$subjectname = array();
					foreach ($subjectnames as $k => $v) {
						$subjectname[] = $v['subject_name'];
					}
					$subjectnamestr = implode(",", $subjectname);
				}

				if (empty($subjectnamestr)) {
					$this->redirect('/info/teacher/index/error/6');  exit;
				}

				//得到学校信息
				$where = ' WHERE "school_id" =' . $data['school_id'];
				$school_info = Nojoin::_getschoolAll($where);
				if (isset($_FILES['file'])) {

					$file_name_list = ZFileUpload::getUniqueID();  //得到唯一名称
					$file_name = $_FILES['file']['name'];
					$extend = pathinfo($file_name);
					$extend = strtolower($extend["extension"]);
					$file_name_list .= '.' . $extend;    //得到文件后缀
					$upload_file_name = UPLOAD_PATH . '/info/' . $file_name_list;
					$file_type = move_uploaded_file($_FILES['file']['tmp_name'], $upload_file_name);
					if ($file_type == 1) {

						spl_autoload_unregister(array('YiiBase', 'autoload'));
						include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel.php');
						include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel/IOFactory.php');
						spl_autoload_register(array('YiiBase', 'autoload'));

						if ($extend == 'xlsx') {
							$type = 'Excel2007';
						} elseif ($extend == 'xls') {
							$type = 'Excel5';
						} else {
							$this->redirect('/info/teacher/index/error/7');    exit;
						}

						$xlsReader = PHPExcel_IOFactory::createReader($type);
						$xlsReader->setReadDataOnly(true);
						$xlsReader->setLoadSheetsOnly(true);
						$Sheets = $xlsReader->load($upload_file_name);
						$Sheet = $Sheets->getSheet(0)->toArray();
						$exm_teacher = array();


						$exm_teacher['exam_id'] = $data['exam_id'];
						$exm_teacher['school_id'] = $school_info[0]['school_id'];
						$exm_teacher['school_name'] = $school_info[0]['school_name'];
						$exm_teacher['addtime'] = time();

						$importruledetail = Array(
						'姓名' => 'teacher_name',
						'科目' => 'subject_name'
						);

						$teacher_sql = array();
						$teacher_error_sql = array();
						$excelcount = count($Sheet);
						if ($excelcount<2){
							$this->redirect('/info/teacher/index/error/8');exit;
						}
						
						foreach ($Sheet as $k => $v) {
							if ($k > 0) {
								if (empty($v[0]) && empty($v[1])){
									unset($v);
								}else {
									$sheetary = array_combine($Sheet[0], $v);
									foreach ($sheetary as $s => $y) {
										if (isset($importruledetail[$s])) {
											$exm_teacher[$importruledetail[$s]] = $y;
										}
									}
									if (empty($v[0]) || empty($v[1]) || !isset($exm_teacher['subject_name']) || !isset($exm_teacher['teacher_name']) ) {
										//数据不存在
										$teacher_error_sql[] = 'INSERT INTO "{{import_error}}" ("excel_row","info","type","exam_id") VALUES (' . $k . ',\'数据字段不能为空\',2,' . $data['exam_id'] . ')';
										continue;
									} else {
										if (strstr($subjectnamestr, $exm_teacher['subject_name'])) {
											$subjectsql = 'SELECT "subject_id" FROM "{{subject}}" WHERE "is_del"=0 AND "subject_name" = :sname ';
											$subject_query = $conn->createCommand($subjectsql);
											$subject_query->bindParam(':sname', $exm_teacher['subject_name'], PDO::PARAM_STR);
											$subject_id = $subject_query->queryRow();
											if (!empty($subject_id)) {
												$exm_teacher['subject_id'] = $subject_id['subject_id'];
											
												if (isset($exm_teacher['teacher_name'])){
												
													$checksql = 'SELECT "teacher_id" FROM "{{teacher}}" WHERE "exam_id" =' . $data['exam_id'] . ' AND "teacher_name" = :tname AND "school_id" = :x_id AND "subject_id" = :k_id ';
													$teacher_query = $conn->createCommand($checksql);
													$teacher_query->bindParam(':tname', $exm_teacher['teacher_name'], PDO::PARAM_STR);
													$teacher_query->bindParam(':x_id',$exm_teacher['school_id'],PDO::PARAM_STR);
													$teacher_query->bindParam(':k_id',$exm_teacher['subject_id'],PDO::PARAM_STR);
													$teacher_id = $teacher_query->queryRow();
														
													
													if (!empty($teacher_id)) {
														//教师已经存在
														$teacher_error_sql[] = 'INSERT INTO "{{import_error}}" ("excel_row","info","type","exam_id") VALUES (' . $k . ',\'教师' . $exm_teacher['teacher_name'] . '已经存在\',2,' . $data['exam_id'] . ')';
														continue;
													}
												}
												
											}
										} else {
											//科目不存在
											$teacher_error_sql[] = 'INSERT INTO "{{import_error}}" ("excel_row","info","type","exam_id") VALUES (' . $k . ',\'该项目不包含科目' . $exm_teacher['subject_name'] .'\',2,' . $data['exam_id'] . ')';
											continue;
										}
										
										if ($exm_teacher) {
											$sqlkey = array_keys($exm_teacher);
											$sqlkey = '"'.implode('","', $sqlkey).'"';
											$sqlvalue = array_values($exm_teacher);
											$sqlvalue = "'" . implode("','", $sqlvalue) . "'";
											$sql = 'INSERT INTO "{{teacher}}" (' . $sqlkey . ') VALUES (' . $sqlvalue . ')';
											$teacher_sql[] = $sql;
										}
									}
								}
							}
						}
						if ($teacher_error_sql) {
							//将本次项目前导入错误日志清空
							$error_where = ' WHERE "type"=2 AND "exam_id"=' . $data['exam_id'];
							Import::_delimporterror($error_where);

							foreach ($teacher_error_sql as $sql) {
								$conn->createCommand($sql)->execute();
							}

							$this->redirect('/info/teacher/index/error/4/exam_id/' . $data['exam_id']);  exit;
						} else {
							foreach ($teacher_sql as $sql) {
								$conn->createCommand($sql)->execute();
							}
						}

						$this->redirect('/info/teacher/index/error/5'); exit;
					}
				}
			}
		}
		$this->redirect('/info/teacher/index');
	}

	/**
     * 下载模版
     * 
     * @version 1.0
     * @update 2014-01-21
     */
	public function actionUpload() {
		spl_autoload_unregister(array('YiiBase', 'autoload'));
		include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel.php');
		include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel/IOFactory.php');
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->setActiveSheetIndex(0)
		->setCellValue('A1', '姓名')
		->setCellValue('B1', '科目');
		$file_nams = "阅卷教师导入模板";
		$file_nams .= ".xls";
		if (preg_match("/MSIE/", $_SERVER["HTTP_USER_AGENT"])) {
			$file_nams = urlencode($file_nams);
			$file_nams = str_replace("+", "%20", $file_nams); // 替换空格
		}
		ob_end_clean();
		header("Content-Type: application/vnd.ms-excel;charset=utf-8");
		header("Content-Disposition: attachment; filename=" . $file_nams);
		header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
		header('Expires:0');
		header('Pragma:public');
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		Yii::app()->end();
		spl_autoload_register(array('YiiBase', 'autoload'));
	}

	//阅卷教师信息导出
	public function actionOutlist() {
		$this->title = '阅卷教师信息导出';
		$ztask = new ZTask();
		$examall = $ztask->_getExamAll();
		$this->render('outlist', array('examall' => $examall));
	}

	/**
     * 	@ 导出Excel
     * 	@ yindebin
     * 	@ 2013-12-13
     *
     */
	public function actionImportExcel() {
		$conn = Yii::app()->db;
		$exam_id = $this->request->getparam('exam_id', 0);
		# 得到科目信息 #
		$where = '';
		$order = '';

		$where.= ' AND "exam_id" = ' . $exam_id;
		$selectSql = 'SELECT * FROM "{{teacher}}"';
		$sql = ' WHERE 1=1  ' . $where;
		$select = $selectSql . $sql . $order;
		$data = $conn->createcommand($select)->queryAll();
		if ($data) {
			foreach ($data as $ke => $one) {
				$subjectinfo = ExamData::_getSubject($one['subject_id']);
				$data[$ke]['subject_name'] = isset($subjectinfo['subject_name']) ? $subjectinfo['subject_name'] : '';
			}
		}
		//if (!empty($data)) {
		spl_autoload_unregister(array('YiiBase', 'autoload'));
		include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel.php');
		include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel/IOFactory.php');

		$objPHPExcel = new PHPExcel();
		$objPHPExcel->setActiveSheetIndex(0)
		->setCellValue('A1', 'ID')
		->setCellValue('B1', '姓名')
		->setCellValue('C1', '密码')
		->setCellValue('D1', '学科');
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(11);
		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(25);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(45);
		$i = 2;
		foreach ($data as $v) {

			$objPHPExcel->setActiveSheetIndex(0)
			->setCellValue('A' . $i, $v['teacher_code'])
			->setCellValue('B' . $i, $v['teacher_name'])
			->setCellValue('C' . $i, $v['teacher_pswd'])
			->setCellValue('D' . $i, $v['subject_name']);
			$i++;
		}
		$objPHPExcel->setActiveSheetIndex(0);
		$file_nams = "阅卷教师信息导出";
		$file_nams .= ".xls";

		if (preg_match("/MSIE/", $_SERVER["HTTP_USER_AGENT"])) {
			$file_nams = urlencode($file_nams);
			$file_nams = str_replace("+", "%20", $file_nams); // 替换空格
		}
		ob_end_clean();
		header("Content-Type: application/vnd.ms-excel;charset=utf-8");
		header("Content-Disposition: attachment; filename=" . $file_nams);
		header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
		header('Expires:0');
		header('Pragma:public');

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');

		Yii::app()->end();
		spl_autoload_register(array('YiiBase', 'autoload'));
		//}
	}

	//ajax获取联动获取学校
	function actionajaxvalue() {
		$exm_id = $this->request->getParam('id');
		$school_info = array();
		if (empty($exm_id)) {
			$schoolwhere = ' WHERE "is_del" =0';
			$school_info = Nojoin::_getschoolAll($schoolwhere);
		} else {
			$exam_where = ' WHERE "exam_id" =' . $exm_id;
			$exam_school = Nojoin::_getexam_schoolALL($exam_where);
			$exam_school_id = array();
			foreach ($exam_school as $k => $v) {
				$exam_school_id[] = $v['school_id'];
			}
			//得到学校信息
			$where = ' WHERE "school_id" IN (' . implode(",", $exam_school_id) . ')';
			$school_info = Nojoin::_getschoolAll($where);
		}
		echo json_encode($school_info);
	}

        //更新功能
    public function actionUpdate(){
        $this->title = '教师信息设置';
        $this->layout = "//layouts/main_window";
        $data = $subjectObject = array();
        $tid = $this->request->getParam('tid');
        $eid = $this->request->getParam('eid');
        $zedu = new ZEdu();
        //得到科目的基本信息
        $subjectObject = $zedu->_getSubjectObject();
        if(!empty($tid)){
            $data = $zedu->_getTeacherInfo($tid,$eid);
}
        //保存更新信息
        if (isset($_POST['submit']) && !empty($_POST['submit'])) {
            $status = $zedu->_updTeacherInfo($_POST['teacher_id'], $_POST,$subjectObject);

            if ($status) {
                $this->frameAjaxMessage('/info/teacher/index');
                exit;
            } else {
                $this->frameAjaxMessage(null, '更新失败');
                exit;
            }
        }
        $this->render('update',array(
            'data'          => $data,
            'subjectObject' => $subjectObject
        ));
    }
    //删除功能
    public function actionDelete(){
        $status = 0;
        $tid = $this->request->getParam('tid');
        $eid = $this->request->getParam('eid');
        if($tid>0 && $eid>0){
            $zedu = new ZEdu();
            $status = $zedu->_delTeacher($tid,$eid);
        }
        echo $status;
    }
}